package StudyCode.summary.myfile;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WriteFileWithFileLock {
	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.wrap("测试文件锁.".getBytes());
		Path path = Paths.get("E:\\迅雷下载\\test1.txt");
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, StandardOpenOption.WRITE)) {
			Future<FileLock> featureLock = asynchronousFileChannel.lock();
			System.out.println("等待文件被锁 ...");
			FileLock lock = featureLock.get();
			if (lock.isValid()) {
				Future<Integer> featureWrite = asynchronousFileChannel.write(buffer, 0);
				System.out.println("等待字节内容写入文件 ...");
				int written = featureWrite.get();
				System.out.println(written + " -> " + path.getFileName());
				lock.release();
			}
		} catch (Exception ex) {
			System.err.println(ex);
		}
	}
}
